<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row>
        <!-- 搜索框 -->
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
          <el-button slot="append" icon="el-icon-search" @click="getUserList()" ></el-button>
        </el-input>
        <!-- 添加按钮 -->
        <el-button type="primary" @click="addUser()">添加用户</el-button>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="name" label="姓名"> </el-table-column>
        <el-table-column prop="Email" label="邮箱"> </el-table-column>
        <el-table-column prop="tel" label="电话"> </el-table-column>
        <el-table-column prop="role" label="角色"> </el-table-column>
        <el-table-column prop="userState" label="状态" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.userState" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作项 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page='queryInfo.pagenum'
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="提示" 
    :visible.sync="dialogVisible"
      width="35%" @close="addFormReset">
      <!-- 内容区域 -->
      <el-form :model="addForm" :rules="userFormRules" ref="rulesFormRef">
        <el-form-item label="用户名" label-width="70px" prop="name">
          <el-input v-model="addForm.name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="70px" prop="password">
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="70px" prop="tel">
          <el-input v-model="addForm.tel" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="addForm.email" autocomplete="off" ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="addNewUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="提示" 
    :visible.sync="editDialogVisible"
      width="35%" @close="editFormReset">
      <!-- 内容区域 -->
      <el-form :model="editForm" :rules="userFormRules" ref="editFormRef">
        <el-form-item label="用户名" label-width="70px">
          <el-input v-model="editForm.name" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="70px" prop="password">
          <el-input v-model="editForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="70px" prop="tel">
          <el-input v-model="editForm.tel" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="editForm.email" autocomplete="off" ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="editUserInfoReq">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 新增用户邮箱验证规则
    let checkEmail = (rule, value, callback) => {
      // 邮箱验证规则-正则表达式
      let regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value)) {
        return callback()
      }
      // 错误回调
      callback(new Error('请输入合法邮箱')) 
    }
    // 新增用户手机号验证规则
    let checkTel = (rule, value, callback) => {
      // 手机号合法验证正则表达式
      let regTel = /^(0|86|17951)?(13[0-9]|15[012356789]|17[235678]|18[0-9]|14[57])[0-9]{8}$/
      // 校验
      if(regTel.test(value)) {
        return callback()
      }
      // 错误回调
      callback(new Error('请输入合法手机号'))
    }
    return {
      // 获取用户列表数据
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 0,
        pagesize: 0
      },
      // 用户列表
      userList: [
        {
          id: "01",
          name: "zs",
          Email: "111@11.com",
          tel: 123456,
          role: "普通用户",
          userState: true,
        },
        {
          id: "02",
          name: "ls",
          Email: "222@11.com",
          tel: 234567,
          role: "普通用户",
          userState: true,
        },
        {
          id: "03",
          name: "ww",
          Email: "333@11.com",
          tel: 345678,
          role: "普通用户",
          userState: true,
        }
      ],
      // 用户总数
      total: 3,
      // 控制提示框是否显示
      dialogVisible: false,
      editDialogVisible: false,
      // 新增用户信息
      addForm: {
        name: 'admin',
        password: '123',
        tel: '15911111111',
        email: 'admin@qq.com'
      },
      // 用户信息验证规则
      userFormRules: {
          name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],  
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],
          tel: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {validator: checkTel, trigger: 'blur'}
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator: checkEmail, trigger: 'blur'}
          ]
        },
      // 修改用户信息
      editForm: {
      }
    }
  },
  // 生命周期函数--进入页面时生效，用于向服务器请求获取用户数据
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
     try {
       let { data: res } = await this.$http.get('users',{ promise: this.queryInfo})
       this.total = res.data.total
       this.userList = res.data.userList
     }
     catch(error) {
       console.log('获取用户列表失败');
     }
    },
    // 页面条数改变事件
    handleSizeChange(val) {
      console.log(val);
      // 根据页面大小（？条/页）的点击变化重新赋值每页显示多少数据的数值
      this.queryInfo.pagesize = val;
      // 然后重新发起axios请求数据
      this.getUserList()
    },
    // 页码跳转事件
    handleCurrentChange(val) {
      console.log(val);
      this.queryInfo.pagenum = val;
      this.getUserList()
    },
    // 用户状态更新
      async userStateChanged(userList) {
        try {
          let {data: res} = await this.$http.put(`users/${userList.id}/state/${userList.userState}`)
          this.$message.success('更新用户状态成功')
        }
        catch(error) {
          this.userList.userState = !this.userList.userState
          console.log(this.userList.userState)
          this.$message.error('更新用户状态失败')
        }
      },
      // 添加用户提示框事件
      // 1，显示添加用户对话框
      addUser() {
        this.dialogVisible = true
      },
      // 2.用户框关闭重置
      addFormReset() {
        this.$refs.rulesFormRef.resetFields()
      },
      // 3.发送添加用户确定事件
      addNewUser() {
        this.$refs.rulesFormRef.validate(async valid => {
          if(!valid) return;
          try{
            let {data: res} = await this.$http.post('users/', addForm)
            this.dialogVisible = false
            this.$message.success('添加用户成功')
            this.getUserList()
          }
          catch(error) {
            this.dialogVisible = false
            this.$message.error('添加用户失败')
          }
        })
      },
      
      // 修改用户提示框事件
      // 1.显示修改用户对话框
       async showEditUser(id) {
         this.editDialogVisible = true
         try{
           const {data: res} = await this.$http.get('users/' + id)
            this.editForm = res.data  
            
         }
          catch(e) {
            this.$message.error('获取用户信息失败')
            console.log(e)
          }
        },
      // 2.修改信息预校验及发送修改确认请求
      editUserInfoReq() {
        this.$refs.editFormRef.validate(async valid => {
          if(!valid) return;
          try{
            const {data: res} = await this.$http.post('user/' + this.editForm.id, {
              password: this.editForm.password,
              tel: this.editForm.tel,
              email: this.editForm.email})
            this.$message.success('修改用户信息成功')
            this.editDialogVisible = false
            this.getUserList()
          }
          catch(e) {
            this.$message.error('修改用户信息失败')
            this.editDialogVisible = false
            console.log(e)
          }
        })
      },
      // 3.修改用户对话框关闭
      editFormReset() {
        this.$refs.editFormRef.resetFields()
      },
      // 删除用户事件
      async delUser(id) {
        // console.log(id)
        const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?',
         '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
          // console.log(confirmRes)
          if(confirmRes !== 'confirm') {
            this.$message.info('已取消删除')
          }
          const {data: res} = await this.$http.delete('users/' + id)
          if(res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.$message.success('删除成功')
          this.getUserList()
      }  
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 500px;
  margin-right: 15px;
}

.el-table {
  margin-top: 15px;
}
</style>